package com.meis.widget.horizontal;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSlider;
import ohos.agp.utils.Rect;
import ohos.app.Context;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

/**
 * Created by wenshi on 2018/12/5.
 * Description tag 判定是否拦截与分发事件
 */
public class InterceptViewPager extends PageSlider {

    private static final String TAG_DISPATCH = "viewpager_dispatch";
    private static final int ACTION_MASK = 255;

    private boolean mInterceptEvent = true;

    public InterceptViewPager(Context context) {
        this(context, null);
    }

    public InterceptViewPager(Context context, AttrSet attrs) {
        super(context, attrs);
    }

    public boolean onInterceptTouchEvent(TouchEvent ev) {
//        int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
        int action = ev.getAction() & ACTION_MASK;
        switch (action) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                MmiPoint point = ev.getPointerPosition(ev.getIndex());
                mInterceptEvent = !childInterceptEvent(this, (int) point.getX(), (int) point.getY());
                break;
        }
//        return mInterceptEvent ? super.onInterceptTouchEvent(ev) : false;
        return mInterceptEvent;
    }

    // 遍历树
    private boolean childInterceptEvent(ComponentContainer parentView, int touchX, int touchY) {
        boolean isConsume = false;
        for (int i = parentView.getChildCount() - 1; i >= 0; i--) {
            Component childView = parentView.getComponentAt(i);
            if (!childView.isComponentDisplayed()) {
                continue;
            }
            boolean isTouchView = isTouchView(touchX, touchY, childView);
            if (isTouchView && childView.getTag() != null && TAG_DISPATCH.equals(childView.getTag().toString())) {
                isConsume = true;
                break;
            }
            if (childView instanceof ComponentContainer) {
                ComponentContainer itemView = (ComponentContainer) childView;
                if (!isTouchView) {
                    continue;
                } else {
                    isConsume |= childInterceptEvent(itemView, touchX, touchY);
                    if (isConsume) {
                        break;
                    }
                }
            }
        }
        return isConsume;
    }

    private boolean isTouchView(int touchX, int touchY, Component view) {
        Rect rect = new Rect();
//        view.getGlobalVisibleRect(rect);
//        return rect.contains(touchX, touchY);
        view.getWindowVisibleRect(rect);
        return rect.contains(touchX, touchY, touchX + 1, touchY + 1);
    }
}
